package cn.cxq.learning.e5;

public class GoldenSection {

    private static int MN = 51;
    private static int RN = 1;
    double OPTX, OPTY, ERR;
    double GOLDEN = 0.6180339887498948;
    double[] A = new double[MN];
    double[] B = new double[MN];
    double[] AX = new double[MN];
    double[] BX = new double[MN];

    double[] X1 = new double[MN];
    double[] X2 = new double[MN];
    double[] Y1 = new double[MN];
    double[] Y2 = new double[MN];

    double A0, B0, EPS = 0.4E-8;

    private double f(double x) {
        return Math.exp(x) - 2 * x * x;
    }

    public GoldenSection(double a0, double b0) {
        A0 = a0;
        B0 = b0;
    }

    public int slove() {
        int K;
        A[0] = A0;
        B[0] = B0;
        BX[0] = (B[0] - A[0]) * GOLDEN;
        AX[0] = BX[0] * GOLDEN;
        X2[0] = A[0] + BX[0];
        Y2[0] = f(X2[0]);
        X1[0] = A[0] + AX[0];
        Y1[0] = f(X1[0]);
        for (K = 1; K < MN; K++) {
            BX[K] = AX[K - 1];
            AX[K] = BX[K] * GOLDEN;
            if (Y1[K - 1] < Y2[K - 1]) {
                A[K] = A[K - 1];
                B[K] = X2[K - 1];
                X2[K] = X1[K - 1];
                Y2[K] = Y1[K - 1];
                X1[K] = A[K] + AX[K];
                Y1[K] = f(X1[K]);
            } else {
                A[K] = X1[K - 1];
                B[K] = B[K - 1];
                X1[K] = X2[K - 1];
                Y1[K] = Y2[K - 1];
                X2[K] = A[K] + BX[K];
                Y2[K] = f(X2[K]);
            }
            if (AX[K] < EPS) break;
        }
        if (K < MN) K++;
        RN = K;
        ERR = AX[RN - 1];
        if (Y1[RN - 1] < Y2[RN - 1]) {
            OPTX = X1[RN - 1];
            OPTY = Y1[RN - 1];
        } else {
            OPTX = X2[RN - 1];
            OPTY = Y2[RN - 1];
        }

        System.out.print(String.format("%.9f %.9f %.9f %.9f %.9f %.9f\n", A[RN - 1], X1[RN - 1], X2[RN - 1], B[RN - 1], Y1[RN - 1], Y2[RN - 1]));

        return 0;
    }

}
